﻿using System.Collections;
using System.Collections.Generic;

using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(ScrollRect))]
public class UGUIScrollView : MonoBehaviour
{
    public int ItemCount
    {
        get
        {
            return items.Count;
        }
    }

    public ScrollRect ScrollRect
    {
        get
        {
            return scrollRect;
        }
    }

    public RectTransform Viewport
    {
        get
        {
            return viewPort;
        }
    }

    public RectTransform Content
    {
        get
        {
            return content;
        }
    }

    [SerializeField]
    protected ScrollRect scrollRect;

    [SerializeField]
    protected RectTransform viewPort;

    [SerializeField]
    protected RectTransform content;

    [SerializeField]
    protected List<GameObject> items = new List<GameObject>();

    // Use this for initialization
    void Start()
    {
        if (scrollRect == null)
        {
            scrollRect = GetComponent<ScrollRect>();
        }

        if (content == null)
        {
            content = scrollRect.content;
        }
    }

    public void AddItem(GameObject go)
    {
        items.Add(go);

        go.transform.SetParent(content);
        go.transform.localScale = Vector3.one;
        go.SetActive(true);
    }

    public GameObject GetItem(int index)
    {
        return items[index];
    }

    public void RemoveItem(GameObject go, bool destroyItem = true)
    {
        items.Remove(go);

        if (destroyItem)
        {
            Destroy(go);
        }
    }

    public void RemoveItemAt(int i, bool destroyItem = true)
    {
        if (i >= 0 && i < items.Count)
        {
            var item = items[i];
            items.RemoveAt(i);

            if (destroyItem)
            {
                Destroy(item);
            }
        }
    }

    public void ClearItems(bool destroyItems = true)
    {
        foreach (GameObject go in items)
        {
            if (go != null && destroyItems)
            {
                Destroy(go);
            }
        }

        items.Clear();
    }
}
